<?php

/**
 * lrn框架之请求相关类
 * 
 * 本文件的思路参考过以下程序，在此一并致谢！
 * - xweibo{@link http://x.weibo.com}
 * 
 * @author Horse Luke<horseluke@126.com>
 * @copyright Horse Luke, 2010
 * @license the Apache License, Version 2.0 (the "License"). {@link http://www.apache.org/licenses/LICENSE-2.0}
 * @version $Id: request.php 140 2010-11-20 14:48:08Z horseluke@126.com $
 * @package lrn_framework
 */
class lrn_request{
    
    /**
     * 获取还原（非转义）后的REQUEST内容，目前只允许以下超级数组（superglobals，简称sg）：
     *  $_GET / $_POST / $_COOKIE / $_REQUEST
     * 
     * @uses lrn_string::stripslashes
     * @param string $sg 需要从哪个超级数组(superglobal)获取。可选值：GET / POST / COOKIE / REQUEST
     * @param string $path 获取的数组索引路径。比如newset、newset/1等
     * @param string $default 默认值。如果该索引变量无设置，那么就返回此值。默认为null
     * @param boolen $emptyCheck 是否进行空值检测？默认为否。
     * @return mixed
     */
    public static function input( $sg, $path, $default = null, $emptyCheck = false ){
        static $sgmap_strip = array('GET', 'POST', 'COOKIE', 'REQUEST');
        
        $sg = strtoupper($sg);
        if( !in_array( $sg, $sgmap_strip ) ){
            return $default;
        }
        
        $temp = $GLOBALS[ '_'. $sg ];
        $path = explode( '/', trim( $path ) );
        foreach ($path as $k => $index) {
            if ( !is_array($temp) || !isset( $temp[$index] ) ) {
                $temp = $default;
                break;
            }
            $temp = $temp[$index];
        }
        
        if( ini_get('magic_quotes_gpc') || ini_get('magic_quotes_sybase') ){
            $temp = lrn_string::stripslashes($temp);
        }
        
        return $temp;
    }
    
    
    /**
     * 获取站点的根部URL（结尾无/）
     * @return string
     */
    public static function baseUrl(){
        static $url = '';
        if ('' === $url) {
            $url = (isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http') .
             '://' . 
            (
                isset( $_SERVER['HTTP_X_FORWARDED_HOST'] ) ? 
                    $_SERVER['HTTP_X_FORWARDED_HOST'] : 
                    ( isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : '') 
            );
        }
        return $url;
    }
    
    
    /**
     * 获取当前运行脚本所在的URL（结尾无/）
     * 该方法将首先从系统config中寻找SITE_URL设置，没有的话，将自动生成并临时存储进系统config中
     * @uses lrn::config
     * @return string
     */
    public static function siteUrl(){
        $url = lrn::config('SITE_URL');
        if ( empty($url) ) {
            $url = self::baseUrl();
            $url .= substr( $_SERVER['SCRIPT_NAME'], 0, strrpos( $_SERVER['SCRIPT_NAME'], '/' ) );
            lrn::config('SITE_URL', $url);
        }
        return $url;
    }
    
}